﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using STT.Business;
using STT.Entities;
using System.Data.OleDb;
using System.Web;
using System.Data;

namespace STT.Admin.UserControls
{
    public partial class ucCap : System.Web.UI.UserControl
    {
        public bool chonSuaClick;
        protected void Page_Load(object sender, EventArgs e)
        {
            LoadCap();
           
        }
        void LoadCap()
        {
            gvCap.AutoGenerateColumns = false;
            gvCap.DataSource = BTbCap.SelectAll1();
            gvCap.DataBind();
        }
        bool KiemTraDuLieu()
        {
            return BTbCap.KiemTraDuLieu(new ETbCap
            {
                TenCap = txtTenCap.Text
            });
        }
        bool KiemTraDuLieu_Sua()
        {
            return BTbCap.KiemTraDuLieu_Sua(new ETbCap
            {
                TenCap = txtTenCap.Text,
                MaCap = Int32.Parse(hfMaCap.Value)

            });
        }
        bool KiemTraMaCap(int MaCap)
        {
            return BTbCap.KiemTraMaCap(new ETbCap
            {
                MaCap = MaCap
            });
        }
        void ThongBao(string Loi)
        {
            ScriptManager.RegisterClientScriptBlock(this, GetType(), "Thông báo!", "<script>alert('" + Loi + "')</script>", false);
        }
        protected void btSearch_Click(object sender, ImageClickEventArgs e)
        {
            gvCap.DataSource = BTbCap.SearchCap(new ETbCap
            {
                TenCap = txtTimKiem.Text
            });

            gvCap.DataBind();
        }

        protected void gvCap_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvCap.EditIndex = -1;
            gvCap.DataBind();
        }

        protected void gvCap_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                int MaCap = int.Parse(gvCap.DataKeys[e.RowIndex].Value.ToString());
                BTbCap.Delete(MaCap);
                LoadCap();
                Session["action"] = 3;
            }
            catch
            {
                ThongBao("Dữ liệu liên quan đến Cấp này vẫn tồn tại, vui lòng kiểm tra lại dữ liệu!");
            }
        }

        protected void gvCap_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvCap.PageIndex = e.NewPageIndex;
            gvCap.DataBind();
        }

        protected void gvCap_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "ChonSua")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                hfMaCap.Value = gvCap.DataKeys[index].Value.ToString();
                // Thay đổi tiêu đề
                txtTieuDe.InnerText = "Sửa Cấp";
                txtTenCap.Text = HttpUtility.HtmlDecode(gvCap.Rows[index].Cells[1].Text);
                Label tt = ((Label)gvCap.Rows[index].Cells[2].FindControl("lblTrangThai"));
                if (tt.Text == "Sử dụng")
                {
                    ddlTrangThai.SelectedValue = "1";
                }
                else
                { ddlTrangThai.SelectedValue = "0"; }
                chonSuaClick = true;
            }
        }

        protected void btSua_Click(object sender, EventArgs e)
        {
            try
            {
                if (!KiemTraDuLieu_Sua())
                {
                    BTbCap.Update(new ETbCap
                    {
                        MaCap = Int32.Parse(hfMaCap.Value),
                        TenCap = txtTenCap.Text,
                        TrangThai = Int32.Parse(ddlTrangThai.SelectedValue)
                    });
                    LoadCap();
                    Session["action"] = 2;
                }
            }
            catch
            {
                ThongBao("Vui lòng kiểm tra lại dữ liệu!");
            }
        }

        //protected void btThemMoi_Click(object sender, EventArgs e)
        //{
        //    if (!KiemTraDuLieu())
        //    {
        //        BTbCap.Insert(new ETbCap
        //        {
        //            TenCap = txtTenCap.Text,
        //            TrangThai = Int32.Parse(ddlTrangThai.SelectedValue)
        //        });

        //        LoadCap();
        //    }
        //    else
        //    {
        //        ThongBao("Cấp này đã tồn tại!");
        //        ScriptManager.RegisterClientScriptBlock(this, GetType(), "Thông báo!", "<script>alert('Cấp này đã tồn tại!')</script>", false);
        //    }
        //}

        protected void btThemExcel_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string FileName = FileUpload1.FileName;
                string[] str = FileUpload1.FileName.Split('.');
                string ten = str[0];
                string duoi = str[1];
                string path = string.Concat(Server.MapPath("~/Uploads/Files/" + ten + Methods.GenerateRandomPassword(3) + "." + duoi));
                FileUpload1.PostedFile.SaveAs(path);
                OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
                OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon);
                OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(command);
                OleDbcon.Open();
                DataTable dt = new DataTable();
                objAdapter1.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        //try
                        //{
                        if (dt.Rows[i][1].ToString() != "" || dt.Rows[i][2].ToString() != "")
                        {
                            if (!KiemTraMaCap(Int32.Parse(dt.Rows[i][1].ToString())))
                            {
                                BTbCap.Insert(new ETbCap
                                {
                                    MaCap = Int32.Parse(dt.Rows[i][1].ToString()),
                                    TenCap = dt.Rows[i][2].ToString(),
                                    TrangThai = Int32.Parse(dt.Rows[i][3].ToString())
                                });
                            }
                        }
                    }
                }
                OleDbcon.Close();
            }
            LoadCap();
            Session["action"] = 1;
        }
        protected void lbXuatDuLieu_Click(object sender, EventArgs e)
        {
           
        }

        protected void lbXoaTat_Click(object sender, EventArgs e)
        {
            try
            {
                for (int i = 0; i < gvCap.Rows.Count; i++)
                {
                    CheckBox cbChon = (CheckBox)gvCap.Rows[i].Cells[0].FindControl("cbChon");
                    if (cbChon != null && cbChon.Checked)
                    {
                        BTbCap.Delete(int.Parse(gvCap.DataKeys[i].Value.ToString()));
                    }
                }

                LoadCap();
                Session["action"] = 3;
            }
            catch
            {
                ThongBao("Dữ liệu liên quan đến một số Cấp vẫn tồn tại, vui lòng kiểm tra lại dữ liệu!");
            }
        }

        protected void btThemMoi_Click(object sender, EventArgs e)
        {
            if (!KiemTraDuLieu())
            {
                BTbCap.Insert(new ETbCap
                {
                    TenCap = txtTenCap.Text,
                    TrangThai = Int32.Parse(ddlTrangThai.SelectedValue)
                });

                LoadCap();
                Session["action"] = 1;
            }
            else
            {
                ThongBao("Cấp này đã tồn tại!");
                //ScriptManager.RegisterClientScriptBlock(this, GetType(), "Thông báo!", "<script>alert('Cấp này đã tồn tại!')</script>", false);
            }
        }
    }
}